from flask import render_template, current_app, session, jsonify, request, g

from info import redis_store, constants
from info.models import User, News, Category
from info.utils.common import set_func
from info.utils.response_code import RET
from . import index_blu


@index_blu.route('/new_list')
def new_list():
    """
    get请求: 传入的是查询参数,所以通过args接收
    :return:
    """
    cid = request.args.get('cid', '1')  # 分类id
    page = request.args.get('page', '1')  # 页数 不传,即获取第一页
    per_page = request.args.get('per_page', '10')  # 每页多少条数据 不传,默认是10条

    # 验证一下传入的查询参数是否正确
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)

    filters = [News.status==0]
    # 如果查询的不是最新数据
    if cid != 1:
        filters.append(News.category_id == cid)

    # 查询数据 paginate里面传入三个参数,第一个参数是页数,第二个参数每页多少条数据,第三个参数是否有错误输出
    paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    new_list = paginate.items  # 模型对象
    # page = paginate.page  # 当前页数
    # new_list = paginate.pages  # 总页数

    new_dict_list = []
    for new in new_list:
        new_dict_list.append(new.to_dict())

    data = {
        'new_dict_list': new_dict_list
    }

    return jsonify(errno=RET.OK, errmsg='查询成功', data=data)



@index_blu.route('/')
@set_func
def index():
    """
    :return:
    """

    # g.user 取出user对象


    news_list = []
    try:
        # --->查询新闻表,右侧排行 这里查询到的是多个模型对象
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    # 定义空的字典列表,里面装的就是字典
    clicks_new_list = []
    # 遍历对象列表,把对象的字典添加到字典列表中
    for new in news_list:
        clicks_new_list.append(new.to_dict())


    # 查询分类数据,通过模板的形式渲染出来
    categories = Category.query.all()

    cate_new_list = []

    for category in categories:
        cate_new_list.append(category.to_dict())



    data = {
        # user.to_admin_dict() if user else None 这段代码是 如果user为True使用 user.to_admin_dict() 否则使用None
        'user_info': g.user.to_dict() if g.user else None,  # user对象的to_admin_dict() 方法,获取到用户的具体信息
        'clicks_new_list': clicks_new_list,
        'category_li': cate_new_list,

    }

    return render_template('news/index.html', data=data )


# 用来加载网站标签小图标
@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')